/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 共配数据监控
 *  */
import React, { useMemo, useCallback, useRef } from 'react';
import { useAntdTable, useDebounceFn } from 'ahooks';
import { useDispatch } from 'dva';
import { Form, DatePicker, Row, Col, Input, Button, message } from 'antd';
import PropTypes from 'prop-types';
import StandardTable from '@/components/StandardTable';
import KbSelect from '@/components/KbSelect';
import moment from 'moment';
import patterns from '@/utils/patterns';
import router from 'umi/router';
import styles from '../style.less';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;

const { phone } = patterns;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};

const scanTimeDefault = [moment('00:00:00', 'HH:mm:SS'), moment('23:59:59', 'HH:mm:SS')];

/* const today = moment()
  .startOf('day')
  .subtract(0, 'days'); */

const disabledDate = current =>
  current &&
  current >
    moment()
      .endOf('day')
      .subtract(0, 'days');

const formatScannerField = scanner => {
  const isPhone = phone.pattern.test(scanner);
  return isPhone ? { cm_phone: scanner } : { cm_name: scanner };
};

const formatScanTimeField = (scanTime = []) => {
  const [start, end] = scanTime;
  const start_scan_time = moment(start).format('YYYY-MM-DD HH:mm:SS');
  const end_scan_time = moment(end).format('YYYY-MM-DD HH:mm:SS');
  return {
    start_scan_time,
    end_scan_time,
  };
};

const formatWaybillNoField = (waybill_no = '') => {
  const formatData = waybill_no.replace(/[\n,]/g, ',');
  const filterData = formatData
    .split(',')
    .filter(i => i)
    .join(',');
  return {
    waybill_no: filterData,
  };
};

/** all字段的替换 */
const formatField = (field = {}) => {
  const { brand, scanType, noticeType } = field;
  return {
    ...field,
    brand: brand === 'all' ? '' : brand,
    scanType: scanType === '全部' ? '' : scanType,
    noticeType: noticeType === '全部' ? '' : noticeType,
  };
};

const scanTypeMap = {
  6: 'send',
  5: 'arrive',
  2: 'delivery',
  3: 'sign',
  4: 'error',
};

const jump = (record = {}) => {
  const { brand_code, waybill_no, phone: rPhone, create_time, cm_name, scan_code } = record;
  const hash = scanTypeMap[scan_code];
  router.push({
    pathname: '/Allocation/GunScanRecord',
    hash: `#${hash}`,
    query: {
      brand: brand_code,
      send_status: '3',
      start_scan_time: moment(create_time).format('YYYY-MM-DD'),
      end_scan_time: moment(create_time).format('YYYY-MM-DD'),
      courier: cm_name,
      cm_phone: rPhone,
      waybill_no,
    },
  });
};

const FormTable = ({ source = 'scan', form }) => {
  const { validateFields, getFieldDecorator, setFieldsValue, resetFields } = form;
  const dispatch = useDispatch();
  const tableList = useRef([]);

  const columns = useMemo(
    () => {
      const arr = [
        {
          width: 200,
          title: '运单号',
          align: 'center',
          dataIndex: 'waybill_no',
          render: (waybill_no, record) => {
            const { scan_code } = record || {};
            const scanArr = Object.keys(scanTypeMap);
            if (scan_code && scanArr.includes(scan_code)) {
              return <a onClick={() => jump(record)}>{waybill_no}</a>;
            }
            return waybill_no;
          },
          show: true,
        },
        {
          width: 100,
          align: 'center',
          title: '扫描类型',
          dataIndex: 'scan_type',
          show: true,
        },
        {
          width: 100,
          align: 'center',
          title: source === 'scan' ? '识别品牌' : '快递品牌',
          dataIndex: 'brand',
          show: true,
        },
        {
          width: 200,
          align: 'center',
          title: '扫描员',
          dataIndex: 'cm_name',
          render: (cm_name, record) => `${cm_name} ${record.phone}`,
          show: true,
        },
        {
          width: 200,
          align: 'center',
          title: '特殊件类型',
          dataIndex: 'notice_type',
          show: source === 'special',
        },
        {
          width: 200,
          align: 'center',
          title: '设备型号',
          dataIndex: 'device',
          show: true,
        },
        {
          width: 200,
          align: 'center',
          title: 'APP版本',
          dataIndex: 'version_code',
          show: source === 'scan',
        },
        {
          width: 200,
          align: 'center',
          title: '扫描时间',
          dataIndex: 'create_time',
          show: true,
        },
        {
          width: 200,
          align: 'center',
          title: '是否开启自动上传',
          dataIndex: 'auto_switch',
          show: source === 'scan',
        },
        {
          width: 200,
          align: 'center',
          title: '删除时间',
          dataIndex: 'deleted_time',
          show: source === 'scan',
        },
      ];

      return arr.filter(i => i.show);
    },
    [source],
  );

  const getTableList = async ({ current }, formData) => {
    const { scanTime = [], scanner, waybill_no, ...rest } = formData;

    const { list = [], pagination = {} } = await dispatch({
      type: 'dataMonitor/getMonitorList',
      payload: {
        page: current,
        tab: source === 'scan' ? 1 : 2,
        ...formatScanTimeField(scanTime),
        ...formatScannerField(scanner),
        ...formatWaybillNoField(waybill_no),
        ...formatField(rest),
      },
    });
    tableList.current = list;
    return {
      list,
      total: pagination.total,
    };
  };

  const { tableProps, search, loading, params, mutate } = useAntdTable(getTableList, {
    defaultPageSize: 20,
    defaultParams: [
      { current: 1, pageSize: 20 },
      { scanTime: scanTimeDefault, scanType: '全部', brand: 'all' },
    ],
    form,
    manual: true,
  });

  const { run: onSubmit } = useDebounceFn(
    () => {
      validateFields((err, values) => {
        if (err) return;
        const { scanTime } = values;
        const [start, end] = scanTime;
        const inMonth = start.month() === end.month();
        if (!inMonth) {
          message.warn('不支持跨月查询，请重新选择查询区间');
          setFieldsValue({
            scanTime: scanTimeDefault,
          });
          return;
        }
        search.submit();
      });
    },
    {
      wait: 300,
      leading: true,
      trailing: false,
    },
  );

  const { run: reset } = useDebounceFn(
    () => {
      tableList.current = [];
      resetFields();
      mutate({ list: [] });
    },
    {
      wait: 300,
      leading: true,
      trailing: false,
    },
  );

  const getAllType = tab =>
    dispatch({
      type: 'dataMonitor/getAllMonitorType',
      payload: {
        tab,
      },
    });

  const getAllBrand = tab =>
    dispatch({
      type: 'dataMonitor/getAllMonitorBrand',
      payload: {
        tab,
      },
    });

  const onExport = useCallback(
    () => {
      const formValue = {};
      const [pagination = {}, formParams = {}] = params;
      [pagination, formParams].forEach(val => {
        Object.keys(val).forEach(i => {
          formValue[i] = val[i];
        });
      });
      const { scanTime = [], scanner, current, pageSize, waybill_no, ...rest } = formValue;

      dispatch({
        type: 'dataMonitor/getMonitorList',
        payload: {
          n_export: 'csv',
          page: current,
          tab: source === 'scan' ? 1 : 2,
          ...formatWaybillNoField(waybill_no),
          ...formatScanTimeField(scanTime),
          ...formatScannerField(scanner),
          ...formatField(rest),
        },
      });
    },
    [params],
  );

  const onDownloadClick = (download, list) => {
    if (list.length === 0) {
      message.warning('暂无可导出数据');
    } else {
      download();
    }
  };

  return (
    <div className={styles.main}>
      <Form {...formItemLayout}>
        <Row>
          <Col xs={24} md={12} lg={8}>
            <FormItem label="扫描日期">
              {getFieldDecorator('scanTime', {
                // console.log(today);
                // initialValue: [today, today],
                initialValue: [
                  // moment(),
                  // moment('YYYY-MM-DD 23:59:59'),
                  moment('00:00:00', 'HH:mm:SS'),
                  moment('23:59:59', 'HH:mm:SS'),
                  // moment(new Date().getTime()).format('YYYY-MM-DD 23:59:59'),
                ],
              })(
                <RangePicker
                  format="YYYY-MM-DD HH:mm:SS"
                  showTime={{ format: 'HH:mm:SS' }}
                  allowClear={false}
                  style={{ width: '100%' }}
                  disabledDate={disabledDate}
                />,
              )}
            </FormItem>
            <FormItem label="扫描类型">
              {getFieldDecorator('scanType', {
                initialValue: '全部',
              })(<KbSelect request={async () => getAllType(1)} format="type" />)}
            </FormItem>
            {source === 'special' && (
              <FormItem label="特殊件类型">
                {getFieldDecorator('noticeType', {
                  initialValue: '全部',
                })(<KbSelect request={async () => getAllType(2)} format="type" />)}
              </FormItem>
            )}
          </Col>
          <Col xs={24} md={12} lg={8}>
            <FormItem label={source === 'scan' ? '识别品牌' : '快递品牌'}>
              {getFieldDecorator('brand', {
                initialValue: 'all',
              })(
                <KbSelect
                  request={() => getAllBrand(source === 'scan' ? 1 : 2)}
                  format="brand*name"
                />,
              )}
            </FormItem>
            <FormItem label="扫描员">
              {getFieldDecorator('scanner')(
                <Input placeholder="请输入扫描员手机号或姓名" allowClear />,
              )}
            </FormItem>
          </Col>
          <Col xs={24} md={12} lg={8}>
            <FormItem label="运单编号">
              {getFieldDecorator('waybill_no')(
                <Input.TextArea
                  style={{ height: '100px' }}
                  allowClear
                  placeholder="请输入运单号编号，多个运单编号按回车分开"
                />,
              )}
            </FormItem>
            <FormItem wrapperCol={{ offset: 6 }}>
              <Row type="flex" gutter={[20, 20]}>
                <Col>
                  <Button type="primary" icon="search" onClick={onSubmit} loading={loading}>
                    查询
                  </Button>
                </Col>
                <Col>
                  <Button
                    icon="download"
                    type="primary"
                    onClick={() => onDownloadClick(onExport, tableList.current)}
                  >
                    导出
                  </Button>
                </Col>
                <Col>
                  <Button type="primary" onClick={reset}>
                    重置
                  </Button>
                </Col>
              </Row>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <StandardTable
        scroll={{ x: 900 }}
        loading={loading}
        rowKey="id"
        data={{
          list: tableProps.dataSource,
          pagination: {
            ...tableProps.pagination,
            showQuickJumper: false,
            showSizeChanger: false,
          },
        }}
        columns={columns}
        onChange={tableProps.onChange}
      />
    </div>
  );
};

FormTable.defaultProps = {
  source: 'scan',
};

FormTable.propTypes = {
  source: PropTypes.oneOf(['scan', 'special']),
};

export default Form.create()(FormTable);
